import React from 'react';
import {View,Text,TouchableOpacity,Button,StyleSheet,ScrollView,Image,TextInput,Modal} from 'react-native';
import '../../global';
import { useState } from 'react';
import * as ImagePicker from 'expo-image-picker';
import AsyncStorage from '@react-native-async-storage/async-storage'
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { AntDesign } from '@expo/vector-icons';
import {useCommendList} from '../../context'
import { useSelector } from 'react-redux';


const getCurrentDay = () =>{
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate;
    }
    let currentdate = year + '-' + month + '-' + strDate;
    return currentdate;
}

const Write = ({navigation}) => {
    const [value,setValue] = useState('');
    const [image,setImage] = useState([]);
    const {commendList,setCommendList} = useCommendList();
    const [modalVisible, setModalVisible] = useState(false);
    const [message,setMessage] = useState('');
    const list=useSelector(state=>state.list)

    const pickImage = async () => {
        let result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.All,
          base64:true,
          quality: 0.1
        });
        if (!result.cancelled) {
          fetch("https://wx.qasdwer.top:8080/pic",{
            method: 'post',
            body: JSON.stringify(result),
            headers: {
              'Content-Type': 'application/json'
            }
        
          })
          .then(res=>res.json())
          .then(res=>{
              console.log(res.addr)
              setImage([...image,res.addr]);
              console.log(image)
            })
        }
    };
    return (
        <View style={styles.con}>
             <View style={[{marginTop:changeH(20)},styles.bg1]}>
                <TouchableOpacity
                style={styles.button1}
                onPress={()=>{
                    if(value == ''){
                        setModalVisible(true);
                        setMessage('请输入评论内容！');
                        setTimeout(()=>{
                            setModalVisible(false);
                        },2000)
                    }
                    else{
                        let time0 = getCurrentDay();
                        let obj = {
                            key0:Date.now(),
                            usernumber:list.account,
                            time0:time0,
                            username:list.name,
                            userimg:list.img,
                            content:value,
                            img:image,
                            comnum:0,
                            likenum:0,
                            coms:[],
                            islike:false,
                        }

                        fetch('https://wx.qasdwer.top:8080/share/write',{
                            method:'put',
                            headers:{
                              'content-type':'application/json;charset=utf-8'
                            },
                            body:JSON.stringify(obj)
                            })
                            .catch((error)=>{
                                console.log("Error");
                                throw error;
                        }); 

                        setCommendList([obj,...commendList]);
                        setModalVisible(true);
                        setMessage('发布成功！');
                        setTimeout(()=>{
                            setModalVisible(false);
                            navigation.navigate('Share');
                        },2000)
                        setImage([]);
                        setValue('');
                        
                    }
                    
                }} >
                    <Text style={styles.font}>发布</Text>
                </TouchableOpacity>
            </View>
            <View>
                <TextInput style={styles.input} multiline={true} placeholder='有啥子评论……' value={value} onChangeText={(text)=>{setValue(text)}}/>
            </View>
            <View style={{marginTop:changeH(50),width:'100%'}}>
                <View style={styles.bg}>
                    <TouchableOpacity  onPress={pickImage} style={styles.button}>
                        <Text style={styles.font}>选择图片</Text>
                    </TouchableOpacity>
                    <Modal
                            transparent={true}
                            visible={modalVisible}
                >
                    <View>
                    <View style={{backgroundColor:'rgba(0,0,0,0.7)',borderRadius:20,
                        display:'flex',justifyContent:'center',alignItems:'center',
                        width:'70%',height:changeH(330),top:0.3*h,left:0.15*w}}>
                        <Text style={{color:'#F5F5F5',fontSize:changeW(35),fontWeight:'bold'}}>{message}</Text>
                    </View>
                    </View>
                </Modal>
                </View>
                <View style={{width:'100%',flexDirection:'row',flexWrap:'wrap'}}>
                {image && image.map((item,index)=>{
                    return(
                        <Image key={index} source={{uri: item}} style={{width:'30%',height:changeH(300),marginLeft:changeW(20),marginTop:changeH(30)}} />
                    ) 
                })}
                </View>
            </View>
           
        </View>
    )
}

const styles = StyleSheet.create({
    con:{
        width:'100%',
        backgroundColor:'#f1f1f1'
    },
    input:{
        width:'95%',
        borderRadius:15,
        height:changeH(230),
        marginLeft:changeW(20),
        backgroundColor:'white',
        color:'black',
        fontSize:changeW(23),
        marginTop:changeH(30),
        paddingLeft:changeW(10),
        paddingBottom:changeH(120)
    },
    button:{
        width:'80%',
        height:changeH(70),
        backgroundColor:'#1E90FF',
        display:'flex',
        alignItems:'center',
        justifyContent:'center'
    },
    font:{
        fontSize:changeW(25),
        fontWeight:'bold',
        color:'white'
    },
    bg1:{
        display:'flex',
        alignItems:'flex-end',
        marginRight:changeW(30)
    },
    bg:{
        display:'flex',
        alignItems:'center',
        justifyContent:'center'
    },
    button1:{
        width:'15%',
        height:changeH(70),
        backgroundColor:'#1E90FF',
        display:'flex',
        borderRadius:10,
        alignItems:'center',
        justifyContent:'center'
    }
})

export default Write